document.addEventListener('DOMContentLoaded', () => {
    // 获取DOM元素
    const createSelection = document.getElementById('create-selection');
    const retrieveSelection = document.getElementById('retrieve-selection');
    const createCard = document.getElementById('create-card');
    const retrieveCard = document.getElementById('retrieve-card');
    const resultCard = document.getElementById('result-card');
    const messageContentCard = document.getElementById('message-content-card');
    const createForm = document.getElementById('create-message-form');
    const retrieveForm = document.getElementById('retrieve-message-form');
    const backButtons = document.querySelectorAll('.back-btn');
    const backToHomeBtn = document.getElementById('back-to-home');
    const backToHomeAfterViewBtn = document.getElementById('back-to-home-after-view');
    const createNewBtn = document.getElementById('create-new');
    const copyLinkBtn = document.getElementById('copy-link');
    const copyIdBtn = document.getElementById('copy-id');
    const copyMessageBtn = document.getElementById('copy-message');
    
    // 初始化页面 - 显示选择卡片
    function showSelectionView() {
        createCard.classList.add('hidden');
        retrieveCard.classList.add('hidden');
        resultCard.classList.add('hidden');
        messageContentCard.classList.add('hidden');
        
        // 重置表单
        if (createForm) createForm.reset();
        if (retrieveForm) retrieveForm.reset();
    }
    
    // 选择发送消息
    if (createSelection) {
        createSelection.querySelector('button').addEventListener('click', () => {
            createCard.classList.remove('hidden');
            createSelection.parentElement.classList.add('hidden');
        });
    }
    
    // 选择接收消息
    if (retrieveSelection) {
        retrieveSelection.querySelector('button').addEventListener('click', () => {
            retrieveCard.classList.remove('hidden');
            retrieveSelection.parentElement.classList.add('hidden');
        });
    }
    
    // 返回按钮
    backButtons.forEach(button => {
        button.addEventListener('click', () => {
            const parentCard = button.closest('.card');
            parentCard.classList.add('hidden');
            document.querySelector('.selection-container').classList.remove('hidden');
        });
    });
    
    // 返回首页按钮
    if (backToHomeBtn) {
        backToHomeBtn.addEventListener('click', () => {
            resultCard.classList.add('hidden');
            document.querySelector('.selection-container').classList.remove('hidden');
        });
    }
    
    // 查看消息后返回首页按钮
    if (backToHomeAfterViewBtn) {
        backToHomeAfterViewBtn.addEventListener('click', () => {
            messageContentCard.classList.add('hidden');
            document.querySelector('.selection-container').classList.remove('hidden');
        });
    }
    
    // 创建新消息按钮
    if (createNewBtn) {
        createNewBtn.addEventListener('click', () => {
            resultCard.classList.add('hidden');
            createCard.classList.remove('hidden');
            createForm.reset();
        });
    }
    
    // 复制链接按钮
    if (copyLinkBtn) {
        copyLinkBtn.addEventListener('click', () => {
            const linkInput = document.getElementById('message-link');
            copyToClipboard(linkInput, copyLinkBtn);
        });
    }
    
    // 复制ID按钮
    if (copyIdBtn) {
        copyIdBtn.addEventListener('click', () => {
            const idInput = document.getElementById('message-id');
            copyToClipboard(idInput, copyIdBtn);
        });
    }
    
    // 复制消息按钮
    if (copyMessageBtn) {
        copyMessageBtn.addEventListener('click', () => {
            const messageContent = document.getElementById('message-content-view').textContent;
            navigator.clipboard.writeText(messageContent).then(() => {
                const originalText = copyMessageBtn.innerHTML;
                copyMessageBtn.innerHTML = '<i class="fas fa-check"></i> 已复制';
                
                setTimeout(() => {
                    copyMessageBtn.innerHTML = originalText;
                }, 2000);
            });
        });
    }
    
    // 复制到剪贴板函数
    function copyToClipboard(input, button) {
        input.select();
        document.execCommand('copy');
        
        const originalText = button.innerHTML;
        button.innerHTML = '<i class="fas fa-check"></i>';
        
        setTimeout(() => {
            button.innerHTML = originalText;
        }, 2000);
    }
    
    // 创建消息表单提交
    if (createForm) {
        createForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const content = document.getElementById('message-content').value;
            const password = document.getElementById('message-password').value;
            
            // 验证密码
            if (!/^\d{6}$/.test(password)) {
                showError(createForm, '密码必须是6位数字');
                return;
            }
            
            // 显示加载状态
            const submitBtn = createForm.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 创建中...';
            
            try {
                const response = await fetch('/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        content: content,
                        password: password
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 显示成功信息和链接
                    document.getElementById('message-id').value = data.message_id;
                    document.getElementById('message-link').value = data.link;
                    
                    // 切换卡片显示
                    createCard.classList.add('hidden');
                    resultCard.classList.remove('hidden');
                } else {
                    showError(createForm, data.error || '创建消息失败，请重试');
                }
            } catch (error) {
                showError(createForm, '发生错误，请重试');
                console.error('Error:', error);
            } finally {
                // 重置按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
            }
        });
    }
    
    // 接收消息表单提交
    if (retrieveForm) {
        retrieveForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const messageId = document.getElementById('message-id-input').value;
            const password = document.getElementById('retrieve-password').value;
            
            // 验证密码
            if (!/^\d{6}$/.test(password)) {
                showError(retrieveForm, '密码必须是6位数字');
                return;
            }
            
            // 显示加载状态
            const submitBtn = retrieveForm.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 获取中...';
            
            try {
                const response = await fetch('/retrieve', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        message_id: messageId,
                        password: password
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 显示消息内容
                    document.getElementById('message-content-view').textContent = data.content;
                    
                    // 切换卡片显示
                    retrieveCard.classList.add('hidden');
                    messageContentCard.classList.remove('hidden');
                } else {
                    showError(retrieveForm, data.error || '获取消息失败，请检查ID和密码');
                }
            } catch (error) {
                showError(retrieveForm, '发生错误，请重试');
                console.error('Error:', error);
            } finally {
                // 重置按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
            }
        });
    }
    
    // 显示错误信息
    function showError(form, message) {
        // 检查是否已存在错误元素
        let errorElement = form.querySelector('.error-message');
        
        if (!errorElement) {
            // 创建错误元素
            errorElement = document.createElement('div');
            errorElement.className = 'error-message';
            errorElement.style.color = 'var(--error-color)';
            errorElement.style.padding = '0.75rem';
            errorElement.style.marginTop = '1rem';
            errorElement.style.backgroundColor = 'rgba(245, 34, 45, 0.1)';
            errorElement.style.borderRadius = '0.25rem';
            errorElement.style.borderLeft = '3px solid var(--error-color)';
            
            // 添加到表单
            form.appendChild(errorElement);
        }
        
        // 设置消息
        errorElement.textContent = message;
        
        // 一段时间后移除
        setTimeout(() => {
            errorElement.style.display = 'none';
            setTimeout(() => {
                errorElement.remove();
            }, 300);
        }, 5000);
    }
    
    // 检查URL哈希值，如果存在则自动填充消息ID
    if (window.location.hash) {
        const messageId = window.location.hash.substring(1);
        if (messageId && retrieveSelection) {
            retrieveSelection.querySelector('button').click();
            document.getElementById('message-id-input').value = messageId;
        }
    }
});
